package com.supermarket.manage.business.cloud.controller;

import com.supermarket.manage.common.dto.CodeStatus;
import com.supermarket.manage.common.dto.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.csource.fastdfs.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.IOException;

/**
 * @author Faxon
 * @version 1.0
 * @date 2020-03-11 17:13
 **/
@RestController
@RequestMapping("/pic")
@Api(value = "PicController", tags = "图片上传接口")
public class PicController {

    @PreAuthorize("hasAuthority('/logined')")
    @ApiOperation(value = "上传图片", notes = "上传图片")
    @PostMapping("/uploadPic")
    public ResponseResult<String> uploadPic(MultipartFile file) {
        if (!isImage(file)) {
            return new ResponseResult<>(CodeStatus.FAIL, "上传失败:非图片文件");
        }
        String url = null;
        try {
            ClientGlobal.initByProperties("config/fastdfs-client.properties");
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer = trackerClient.getConnection();
            StorageServer storageServer = trackerClient.getStoreStorage(trackerServer);
            StorageClient storageClient = new StorageClient1(trackerServer, storageServer);
            String filename = file.getOriginalFilename();
            String extName = filename.substring(filename.lastIndexOf(".") + 1);
            String[] strings = storageClient.upload_file(file.getBytes(), extName, null);
            if (strings != null && strings.length == 2) {
                String fileId = strings[0] + "/" + strings[1];
                url = fileId;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StringUtils.isBlank(url)) {
            return new ResponseResult<>(CodeStatus.FAIL, "上传失败");
        }
        return new ResponseResult<>(CodeStatus.OK, "上传成功", url);
    }

    /**
     * 判断是否是图片
     *
     * @param file
     * @return
     */
    private boolean isImage(MultipartFile file) {
        try {
            // 通过ImageReader来解码这个file并返回一个BufferedImage对象
            // 如果找不到合适的ImageReader则会返回null，我们可以认为这不是图片文件
            // 或者在解析过程中报错，也返回false
            Image image = ImageIO.read(file.getInputStream());
            return image != null;
        } catch (IOException ex) {
            return false;
        }
    }
}
